﻿
using System;
using System.Reflection;

namespace IQIGame.Onigao.Framework
{
    public class Singleton<T> where T : Singleton<T>
    {

        private static T m_Instance;

        public static T Instance
        {
            get
            {
                if (m_Instance == null)
                {
#if UNITY_EDITOR
                    Type type = typeof(T);

                    ConstructorInfo[] constructors = type.GetConstructors();

                    foreach (ConstructorInfo constructor in constructors)
                    {
                        if (constructor.IsPublic)
                        {
                            UnityEngine.Debug.LogError($"单例{type.Name}不能含有公共构造函数。");
                            break;
                        }
                    }

                    ConstructorInfo constructor2 = type.GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, null, Type.EmptyTypes, null);
                    if (constructor2 == null)
                    {
                        UnityEngine.Debug.LogError($"单例{type.Name}必须包含私有无参构造函数。");
                    }
#endif
                    m_Instance = (T)Activator.CreateInstance(typeof(T), true);
                }
                return m_Instance;
            }
        }

        protected Singleton()
        {
        }
    }
}
